package cn.doitedu.basic.mr;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;

public class MapJoin {

    public static class MapJoinMapper extends Mapper<LongWritable, Text,Text, NullWritable>{
        HashMap<String, String> dictB = new HashMap<>();
        @Override
        protected void setup(Context context) throws IOException, InterruptedException {

            BufferedReader br = new BufferedReader(new FileReader("b1.txt"));
            String line = null;
            while((line=br.readLine())!=null){
                String[] split = line.split(",");
                dictB.put(split[0],line);
            }


        }


        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

            String did = value.toString().split(",")[1];
            String b_data = dictB.get(did);

            context.write(new Text(value.toString()+","+b_data),NullWritable.get());

        }
    }

    public static void main(String[] args) throws Exception {

        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);

        job.setJarByClass(MapJoin.class);


        job.setMapperClass(MapJoinMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(NullWritable.class);


        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);


        FileInputFormat.setInputPaths(job,new Path("basic_knowledge/data/join/t_a"));
        FileOutputFormat.setOutputPath(job,new Path("basic_knowledge/data/join/output"));

        job.addCacheFile(new URI("hdfs://doitedu01:8020/cachefiles/b1.txt"));


        boolean b = job.waitForCompletion(true);
        System.exit(b?0:2);

    }


}
